java RSA Encryption生成带有“\n”字符的字符串,我无法解密
我试图用java创建一个简单的实用程序类,用RSA公钥加密字符串,但我的代码生成了一个带有“\n”字符的加密字符串,无法在服务器上解密
这是我的代码:
private static String ALGORITHM = "RSA";
private static String TRANSFORMATION = "RSA/None/OAEPWithSHA1AndMGF1Padding";
private String encryptData(String txt, SecurityCallback callback) {
String encoded = "";
byte[] encrypted = null;
try {
String publicKeyContent = getPublicKeyString();
PublicKey pubKey = stringToPublicKey(publicKeyContent);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
encrypted = cipher.doFinal(txt.getBytes(StandardCharsets.UTF_8));
encoded = Base64.encodeToString(encrypted, Base64.DEFAULT);
} catch (Exception exception) {
callback.onError(exception);
}
return encoded;
}
private String getPublicKeyString() {
return PUBLIC_KEY.replaceAll("\\n", "").replace("-----BEGIN PUBLIC KEY-----", "").replace("-----END PUBLIC KEY-----", "");
}
private PublicKey stringToPublicKey(String stringKey) throws InvalidKeySpecException,
NoSuchAlgorithmException {
byte[] keyBytes = Base64.decode(stringKey, Base64.DEFAULT);
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
return keyFactory.generatePublic(spec);
}
我的公钥是
----开始公开密钥----- Hasdjasjkfhajdhjahskfjhasjkfhajkfhkaj -----结束公钥-----
# 1 楼答案
问题是,在Android中使用该代码生成的加密文本带有一些行尾字符,而后端在尝试转换字符串时出错。所以我通过替换那些末端字符来修复它
不确定为什么在加密过程中添加这些字符